package la.bbs558.util;

import cn.hutool.core.lang.Snowflake;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import la.bbs558.entity.enums.OssFolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @author: Shanks
 * @date: 2023/12/15 10:11
 * @desc: 操作oss文件
 */
@Component
@Slf4j
public class OssUtil {
    @Value("${oss.id}")
    private String secretId;
    @Value("${oss.key}")
    private String secretKey;

    @Value("${oss.region-name}")
    private String regionName;

    @Value("${oss.bucket-name}")
    private String bucketName;

    @Value("${oss.visit-url}")
    private String visitUrl;

    @Resource
    @Lazy
    private Snowflake snowflake;

    private COSClient getCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        Region region = new Region(regionName);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

    public String uploadFile(InputStream file, OssFolder folder, String fileName) {
        COSClient cosClient = getCOSClient();
        try {

            String key = folder.getFolder() + "/" + getFileName(fileName);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file, null);
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            cosClient.putObject(putObjectRequest);
            return key;
        } finally {
            cosClient.shutdown();
        }
    }

    @SneakyThrows
    public String uploadFile(MultipartFile file, OssFolder folder, String fileName) {
        return uploadFile(file.getInputStream(),folder,fileName);
    }

    public String uploadFile(MultipartFile file, OssFolder folder) {
        return uploadFile(file, folder, file.getOriginalFilename());
    }

    private String getFileName(String fileName) {
        // 获取文件后缀，获取之前判断是否有后缀
        String suffix = "";
        if (fileName.contains(".")) {
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        return snowflake.nextIdStr() + suffix;
    }

    public String getFullUrl(String key) {
        return visitUrl + key;
    }
}
